//
//  CategoryListViewController.swift
//  ToDoList
//
//  Created by Qingke on 16/4/14.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class CategoryListViewController: UITableViewController, CatgoryDetailDelegate, UINavigationControllerDelegate {

    var category: Category!
    var dataModel: DateModel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        loadTc()
       dataModel.loadCategory()
 }
    
    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
        if viewController === self {
            dataModel.selectedCategoryIndex = -1
        }
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.delegate = self
        
        if (dataModel.selectedCategoryIndex >= 0 && dataModel.selectedCategoryIndex < dataModel.categories.count) {
            performSegueWithIdentifier("showTasks", sender: dataModel.categories[dataModel.selectedCategoryIndex])
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func catgoryViewController(controller: CatgoryDetaiViewController, didFinishAddtask category: Category) {
        dataModel.categories.append(category)
        dataModel.sortCategory()
//        let indexPath = NSIndexPath(forRow: dataModel.categories.count - 1 , inSection: 0)
//        tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        tableView.reloadData()
        dataModel.saveCategoryList()
    }
    func catgoryViewController(controller: CatgoryDetaiViewController,didFinishEditask category: Category){
        let index = dataModel.categories.indexOf(category)
        
        if let index = index {
            let indexPath = NSIndexPath(forRow: index, inSection: 0)
            let cell = tableView.cellForRowAtIndexPath(indexPath)
            cell?.textLabel!.text = category.name
            
        }
        
        dataModel.saveCategoryList()
        
    }


    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return dataModel.categories.count
    }

    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellIdentifier = "cell"
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellIdentifier)// 设置subtitle  可以设置detail
            cell?.accessoryType = .DetailDisclosureButton
        }
        //Count=0 没有任务
        //opentask = 0  全部完成
        let tc = dataModel.categories[indexPath.row]
        cell?.textLabel?.text = tc.name
        cell?.detailTextLabel?.text = "\(tc.openTaskCount())项待办"
        // Configure the cell...
        //设置icon
        cell?.imageView?.image = UIImage(named: tc.iconName)
        return cell!
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let taskCatgory = dataModel.categories[indexPath.row]
        
        //记忆
        dataModel.selectedCategoryIndex = indexPath.row
        
        performSegueWithIdentifier("showTasks", sender: taskCatgory)
    }

    override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
        
                let navigation = storyboard!.instantiateViewControllerWithIdentifier("categoryVC") as! UINavigationController
                let controller = navigation.topViewController as! CatgoryDetaiViewController
                let category = dataModel.categories[indexPath.row]
        
                controller.catgoryDelegate = self
                controller.categoryToEdit = category
        
                presentViewController(navigation, animated: true, completion: nil)
        
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        
        if segue.identifier == "showTasks" {
            let taskVc = segue.destinationViewController as! TaskListViewController
            let taskCatgory = sender as! Category
            taskVc.category = taskCatgory
            
        }else if segue.identifier == "addTaskCatgory" {
            
            let navigationVC = segue.destinationViewController as! UINavigationController
            let addTaskVC = navigationVC.topViewController as! CatgoryDetaiViewController

//            let category = sender as! Category
//            addTaskVC.categoryToEdit = category
            addTaskVC.catgoryDelegate = self
        }
    }

    //删除某一个行
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        dataModel.categories.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    }
    
}












